import string
import sys
import cgi
import types
import traceback
import urllib
import md5
import time

import genx_helpers
genx_helpers.add_module('aumfp')

import genx_metaweb
import genx_transfill
import genx_helpers
import genx_errors

import bm_cfg
import bm_text
import bm_extract
from bm_log import Log

import hcard
import vcard

searchd = {
	"title" : "People",
	"source" : "hCard, by URL",
	"templated" : {
		"gencard-uf" : {
			"title" : "GenCard",
			"title_full" : "GenCard for Microformats",
			"caps" : [ 
				genx_helpers.CAP_GENCARD,
				genx_helpers.CAP_HTML, 
				genx_helpers.CAP_MICROFORMATS, 
				genx_helpers.CAP_HCARD,
			],
		},
		"simple-uf" : {
			"title" : "Simple",
			"title_full" : "Simple for Microformats",
			"caps" : [ 
				genx_helpers.CAP_HTML, 
				genx_helpers.CAP_MICROFORMATS, 
				genx_helpers.CAP_HCARD,
			],
		},
	},
}

CACHE = False
MAX_RESULTS = 30

loose_fields = [
	"org",
	"street_address",
	"locality",
	"region",
	"country_name",
	"postal_code",
	"email",
	"tel",
	"mobile",
	"fax",
]

def query(cfg, searchd, name, application, retry = 0):
	uris = bm_extract.as_list(cfg, "net-hcard.uris")
	for uri in uris:
		yield None

		rds = []
		for resultd in hcard.MicroformatHCard(page_uri = uri).Iterate():
			vcard.scrub_address(resultd)
			iid = application.MakeIID("%s/%s" % ( resultd['@index'], resultd['@uri'], ))

			rd = {
				genx_helpers.KEY_IID : iid,
				genx_helpers.KEY_TITLE_SHORT : resultd['@title'],
				genx_helpers.KEY_TITLE_FULL : resultd['@title'],
				genx_helpers.KEY_TITLE_LIST : resultd['@title'] or name or '',
			}

			photo = resultd.find('photo')
			if photo:
				rd[genx_helpers.KEY_IMAGE_URI] = photo

			home_uri = resultd.find('url')
			if home_uri:
				try: home_uri = urllib.unquote(home_uri)
				except: pass

				rd['home_uri'] = home_uri

			for field in loose_fields:
				value = resultd.find(field.replace("_", "-"))
				if value:
					rd[field] = value

			if not bm_extract.search(o = rd, paths = [ genx_helpers.KEY_TITLE_FULL, "org", ], query = name):
				continue

			rds.append(rd)

		rds.sort(lambda a, b: cmp(a[genx_helpers.KEY_TITLE_LIST], b[genx_helpers.KEY_TITLE_LIST]))

		for rd in rds:
			yield	rd
